package com.yiboshi.rehrs.helper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yiboshi.rehrs.common.VarConstant;
import com.yiboshi.rehrs.common.ZhongConfig;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.domain.service.IZhongUserService;
import com.yiboshi.rehrs.exception.ZhongException;
import com.yiboshi.rehrs.exception.ZyantExceptionUtils;
import com.yiboshi.rehrs.param.ZhongReq;
import com.yiboshi.rehrs.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author jack 2025/3/17
 */
@Slf4j
public abstract class HelperZhong {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ZhongConfigHelper configHelper;

    @Autowired
    IZhongUserService zhongUserVipService;

    @Autowired
    ProxyHelper proxyHelper;


    public String x_user_key(String account) {
        String x_user_key = "z:x-user:" + getMode() + ":" + account;
        return x_user_key;
    }

    public abstract int getMode();


    public ZhongUser getVipUserDB(int mode) {
        String key = "getCacheVipUser" + mode;
        ZhongUser zhongUser = CacheUtils.getByCache10Hour(key, ZhongUser.class);
        if (zhongUser != null) {
            return zhongUser;
        }
        LambdaQueryWrapper<ZhongUser> lambdaQueryWrapper = zhongUserVipService.getQueryWrapper().eq(ZhongUser::getMode, mode)
                .gt(ZhongUser::getVipExpDate, LocalDateTime.now().plusHours(3))
                .eq(ZhongUser::getDeleted, 0)
                .last("order by rand() limit 1");
        zhongUser = zhongUserVipService.getOne(lambdaQueryWrapper);
        if (zhongUser != null) {
            CacheUtils.putByCache10Hour(key, zhongUser);
        }
        return zhongUser;
    }




    public JSONObject send(ZhongReq zhongReq, String finalUri) {
        //String finalUri = "logon";
        ZhongConfig zhongConfig = getZhongConfig();
        List<String> domains = zhongConfig.getDomains();
        String domain = zhongConfig.getDomain();
        if(!CollUtil.isEmpty(domains)){
            domain = domains.get(AperStringUtils.randomNum(domains.size()));
        }
        String api = domain + finalUri;
        String reqBody = zhongReq.getData();
        String sign = zhongReq.getSign();
        JSONObject end = JSONBuilder.start()
                .put("data", reqBody).put("sign", sign).end();
        Map<String, String> headerMap = zhongConfig.getHeaderMap();
        String originData = zhongReq.getOriginData();
        int i = 0;
        String executeRes = "";
        //错误重试
        try {
            long timeStart = System.currentTimeMillis();
            OkHttpUtil post = new OkHttpUtil().retryCount(3)
                    .timeoutMillis(600)
                    .headers(headerMap)
                   // .proxySupplier(() -> proxyHelper.one())
                    .url(api)
                    .post(end.toJSONString());

            if(!RehrsSystemConfig.isDev()){
                post.proxySupplier(() -> proxyHelper.one());
            }
            executeRes = post.execute();
            long timeEnd = System.currentTimeMillis();
            //log.info("daxiang cps header 耗时:{} ms",(timeEnd-timeStart));
            //HttpHost httpHost = proxyHelper.one();
           //log.info("api:{} ，httpHost:{} originData:{}",api,httpHost,originData);
           //httpResponse = HttpClientUtils.doPostProxy(api, headerMap, end.toJSONString().getBytes()
            //        , httpHost);

            JSONObject jsonObject = JSONObject.parseObject(executeRes);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            if (!Objects.equals(code, "200")) {
                log.error("url:{} origin:{} jsonObject:{}", api, zhongReq.getOriginData(), jsonObject);
                if(msg.contains("无效Token令牌")){
                    deleteVipTokenCache();
                }
                ZyantExceptionUtils.x(true,msg);
            }
            String dataStr = jsonObject.getString("data");
            return decode(dataStr);
        } catch (ZhongException e) {
            throw  e;
        }catch (Exception e) {
            log.error("url:{} origin:{},", api, zhongReq.getOriginData());
            log.error("", e);
            ZyantExceptionUtils.x(true,"授权异常，请稍后再试");
        }
        return null;



    }

    protected abstract void deleteVipTokenCache();

    public Map<String, String> meger(Map<String, String> map) {
        Map<String, String> map1 = configHelper.fiddleMap();
        map1.putAll(map);


        //map.put("person_no", person_no);
        /*if(Objects.equals(type,"newCallAndFile")){
            mapRes.put("user-agent","okhttp/3.10.0");
            mapRes.put("content-type","application/x-www-form-urlencoded; charset=utf-8");
        }*/
        return map1;
    }

    public String data_init(String s, JSONObject zhongReq) {
        String[] split = s.split(",");
        StringBuilder stringBuilder = new StringBuilder();
        for (String s1 : split) {
            String string = zhongReq.getString(s1);
            if (StrUtil.isEmpty(string)) {
                string = "";
            }
            if (stringBuilder.length() > 0) {
                stringBuilder.append("&");
            }
            stringBuilder.append(s1).append("=").append(string);
        }

        return stringBuilder.toString();
    }


    protected abstract JSONObject decode(String dataStr);


    protected abstract ZhongConfig getZhongConfig();


    public abstract Map<String, String> vipHeader(ZhongUser zhongSessionUser, ZhongReq zhongReq);

    public abstract Map<String, String> channelHeader(String uri, ZhongUser zhongUser);

    public abstract Map<String, String> logonHeader(ZhongReq zhongReq);

    public String vipTokenKey(){
        return "system:vip_"+getMode()+":"+VarConstant.DX_VIP_ACCOUNT;
    }


    public static int getTimeOut(String type) {
        if(type==null){
            return 0;
        }
        if(type.contains("queryUnfinishone")){
            //接口-段信息查询
            return 30;
        }
        if(type.contains("traceInfo/query")){
            //轨迹查询 18个小时缓存
            return 10;
        }
        /*if(type.contains("common/putOrgInfo")){
            return 3600*24*10;
        }*/
        /*if(type.contains("findwaybillnoinfoone")){
            //下段查询
            return 0;
        }
        if(type.contains("makereceiveonemixed")){
            //下段
            return 0;
        }*/

        if(!type.contains("newCallAndFile")){
            return 0;
        }
        int time = 150+AperStringUtils.randomNum(30);
        //time = 0;
        return time;
    }
}
